package de.koller.planet2D.frame.previewRender;

import de.koller.oceanFramework.math.Vec;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;

public class CameraSteerListener extends MouseAdapter {
	
	private final Camera camera;
	private Vec lastPoint = null;
	private boolean down = false;
	
	public CameraSteerListener( Camera camera ) {
		this.camera = camera;
	}

	@Override
	public void mouseDragged( MouseEvent e ) {
		if( !down )
			return;
		if( lastPoint == null ) 
			lastPoint = new Vec( e.getPoint() );
		
		double mx = (e.getPoint().getX() - lastPoint.getX());
		double my = (e.getPoint().getY() - lastPoint.getY());
		camera.pos.add( mx, my );
		lastPoint.set( e.getPoint() );
		camera.proot.updateThis();
	}

	@Override
	public void mouseWheelMoved( MouseWheelEvent e ) {
		super.mouseWheelMoved( e );
		
		int v = e.getWheelRotation() > 0 ? 1 : -1;
		
		float zoomFact = 1.05f;
		double cx = camera.pos.getX();
		double cy = camera.pos.getY();
		
		cx -= e.getPoint().x;
		cy -= e.getPoint().y;

		if( v < 0 ) {
			camera.scale *= zoomFact;
			cx *= zoomFact;
			cy *= zoomFact;
		} else {
			camera.scale /= zoomFact;
			cx /= zoomFact;
			cy /= zoomFact;
		}

		cx += e.getPoint().x;
		cy += e.getPoint().y;
		
		camera.pos.set( cx, cy );
		camera.proot.updateThis();
	}
	
	@Override
	public void mouseExited( MouseEvent e ) {
		super.mouseExited( e );
		resetDrag();
	}

	@Override
	public void mouseMoved( MouseEvent e ) {
		super.mouseMoved( e );
		resetDrag();
	}

	@Override
	public void mouseReleased( MouseEvent e ) {
		super.mouseReleased( e );
		resetDrag();
	}

	@Override
	public void mousePressed( MouseEvent e ) {
		super.mousePressed( e );
		
		down = e.getButton() == 3;
	}
	
	
	private void resetDrag() {
		lastPoint = null;
	}
	
}
